//
//  UserInfoController.m
//  QQplayground
//
//  Created by zhangxy on 2018/6/7.
//  Copyright © 2018年 zhang. All rights reserved.
//

#import "UserInfoController.h"

#import "ZZHomeCell.h"
#define cellIdentifier @"ZZHomeCell"

#import "ZZUserInfoCell.h"

#import <MJRefresh.h>
#import "SettingController.h"
#import "SettingController.h"

@interface UserInfoController (){
    int page;
}

@property(nonatomic,strong)UITableView      *listTable;
@property(nonatomic,strong)NSMutableArray   *listArray;
@property(nonatomic,strong)ZZUserInfoCell   *headerCellView;
@property(nonatomic,strong)User *user;


@end

@implementation UserInfoController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //    [self setNavigationBar];
    self.navigationController.navigationBar.hidden = YES;
    
    // Do any additional setup after loading the view.
    [self createTableView];
    if (@available(iOS 11.0, *)) {
        self.listTable.contentInsetAdjustmentBehavior = UIApplicationBackgroundFetchIntervalNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = false;
        // Fallback on earlier versions
    }
    
    
    self.menuLeftButton=[UIButton buttonWithType:UIButtonTypeCustom];
    [self.menuLeftButton setFrame:CGRectMake(10, StatusBarHeight, 60, 44)];
    self.menuLeftButton.tag=BACK_BUTTON;
    [self.menuLeftButton.titleLabel setFont:ListTitleFont];
    [self.menuLeftButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.menuLeftButton setTitleColor:UIColorFromRGBAlpha(TextWhiteColor, 0.7) forState:UIControlStateHighlighted];
    [self.menuLeftButton addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.menuLeftButton.imageView setContentMode:UIViewContentModeScaleAspectFit];
    [self.menuLeftButton setImage:[UIImage imageNamed:@"btn_back_title_sel"] forState:UIControlStateNormal];
    [self.menuLeftButton setImage:[UIImage imageNamed:@"btn_back_title_sel"] forState:UIControlStateHighlighted];
    [self.menuLeftButton setAutoresizingMask:UIViewAutoresizingFlexibleRightMargin];
    [self.menuLeftButton setTitle:@"   " forState:UIControlStateNormal];
    [self.view addSubview:self.menuLeftButton];
    
    self.menuRightButton=[UIButton buttonWithType:UIButtonTypeCustom];
    [self.menuRightButton setFrame:CGRectMake(ScreenWidth-44, StatusBarHeight, 44, 44)];
    self.menuRightButton.tag=RIGHT_BUTTON;
    [self.menuRightButton.titleLabel setFont:ListTitleFont];
    [self.menuRightButton addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.menuRightButton.imageView setContentMode:UIViewContentModeScaleAspectFit];
    [self.menuRightButton setImageEdgeInsets:UIEdgeInsetsMake(5, 5, 5, 5)];
    [self.menuRightButton setImage:[UIImage imageNamed:@"Combined Shape"] forState:UIControlStateNormal];
    [self.menuRightButton setImage:[UIImage imageNamed:@"Combined Shape"] forState:UIControlStateHighlighted];
    [self.menuRightButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.menuRightButton setTitleColor:UIColorFromRGBAlpha(TextWhiteColor, 0.7) forState:UIControlStateHighlighted];
    [self.menuRightButton setTitleColor:UIColorFromRGBAlpha(TextWhiteColor, 0.7) forState:UIControlStateDisabled];
    [self.menuRightButton setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
    [self.view addSubview:self.menuRightButton];
    
    MJRefreshAutoStateFooter *footer = [MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
        [self loadMoreData];
    }];
    _listTable.footer = footer;
    [_listTable reloadData];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = YES;
}
-(void)buttonClick:(UIButton *) sender{
    [super buttonClick:sender];
    if(sender.tag == RIGHT_BUTTON){
        SettingController *vc = [[SettingController alloc] init];
        [self openPushVC:vc];
    }
}

-(void)createTableView{
    page = 1;
    _listArray = [[NSMutableArray alloc] init];
    _listTable=[self.view createTableView:self cell:cellIdentifier];
    [_listTable setFrame:self.view.bounds];
    
    [_listTable setBackgroundColor:UIColor.whiteColor];
    
    if (iOS7) {
        _listTable.backgroundView = nil;
    }
    
    
    
    [_listTable setSeparatorColor:LINE_COLOR];
    [_listTable setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
    _listTable.tableHeaderView = [self headerView];
    [self setTableSeparatorInset];
    
//    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        [self loadBegin];
//    }];
//    _listTable.header = header;
    
    _user = [UserUtil getUser];
    [self loadBegin];
}


-(void)getUesrInfo{
    [NetworkUtil POST:API_UserInfo parameters:@{@"user_id":convertToString(_user_id),@"is_all":@"1"} success:^(id responseObject, NSDictionary *dict) {
        _user = [[User alloc] initWithDictionary:dict[@"data"]];
        [_listTable reloadData];
    } failure:^(NSError *error, NSString *message) {
        [PopUtil showMessage:message positionType:PopPositionTypeMiddle];
    }];
}

-(void)loadBegin{
    //    [_listArray removeAllObjects];
    [self loadMoreData];
}


/**
 加载更多
 */
-(void)loadMoreData{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSDictionary *p = @{@"user_id":@"2666684",//convertIntToString((int)[UserUtil getUser].user_id),
                        @"nav_type":@"all",
                        @"page":convertIntToString(page),
                        @"page_size":@"20"
                        };
    [NetworkUtil POST:API_GetHomeList parameters:p success:^(id responseObject,NSDictionary *dictionary) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if([self.listTable.header isRefreshing]){
            [self.listTable.header endRefreshing];
        }
        if([self.listTable.footer isRefreshing]){
            [self.listTable.footer endRefreshing];
        }
        
        DLog(@"%@",dictionary);
        
        NSArray *arr = dictionary[@"data"][@"list"];
        for(NSDictionary *item in arr){
            [self.listArray addObject:[[ZZHomeTopicEntity alloc] initWithDictionary:item]];
        }
        [self.listTable reloadData];
        if([dictionary[@"data"][@"page"] intValue] < [dictionary[@"data"][@"pages"] intValue]){
            page = [dictionary[@"data"][@"page"] intValue] + 1;
        }
        
    } failure:^(NSError *error,NSString *message) {
        if([self.listTable.header isRefreshing]){
            [self.listTable.header endRefreshing];
        }
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}


- (UIView *)headerView
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 398+NavBarHeight)];
    
    User *user = [UserUtil getUser];
    if(ZC_iPhoneX){
        _headerCellView = [[NSBundle mainBundle]loadNibNamed:@"ZZUserInfoCell" owner:nil options:nil].firstObject;
    }else{
        _headerCellView = [[NSBundle mainBundle]loadNibNamed:@"ZZUserInfoCell" owner:nil options:nil].firstObject;
    }
    [_headerCellView setFrame:CGRectMake(0, NavBarHeight, ScreenWidth, 398)];
    [_headerCellView dataToView:user];
    
    UIImage *backImage =[UIImage imageNamed:@"voice_bg"];
    headerView.layer.contents=(id)backImage.CGImage;
    //    self.view.layer.backgroundColor = [UIColor clearColor].CGColor;
    headerView.layer.backgroundColor = UIColorFromRGB(0x67ACA6).CGColor;
    
    
    [headerView addSubview:_headerCellView];
    
    return headerView;
}



#pragma mark UITableView delegate Start
// 返回section数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

// 返回section高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0;
}

// 返回section 的View
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectZero];
    if(section == 0){
        [headerView setBackgroundColor:UIColor.clearColor];
        //        [headerView setFrame:CGRectMake(0, 0, ScreenWidth, 100.0f)];
        
        //        UserHeaderCell *cellView = [self headerView];
        //        [cellView setFrame:CGRectMake(0, 54, ScreenWidth, 85)];
        //        [cellView dataToView:[UserUtil getUser]];
        //        [headerView addSubview:cellView];
        
        
        [_headerCellView dataToView:_user];
    }else{
        [headerView setBackgroundColor:UIColorFromRGB(BgSystemColor)];
        [headerView setFrame:CGRectMake(0, 0, ScreenWidth, 10.0f)];
        
    }
    return headerView;
}

// 返回section下得行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _listArray.count;
}

// cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ZZHomeCell *cell = (ZZHomeCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[ZZHomeCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    
    
    [cell dataToView:[_listArray objectAtIndex:indexPath.row]];
    
    return cell;
}



// 是否显示删除功能
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}

// 删除清理数据
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    editingStyle = UITableViewCellEditingStyleDelete;
}


// table 行的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    return 70.0f;
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}

// table 行的点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //    VipModel *model=[_listArray objectAtIndex:indexPath.section];
    ZZHomeTopicEntity *items = _listArray[indexPath.section];
    
    
    
}

//设置分割线间距
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if((indexPath.section+1) < _listArray.count){
        UIEdgeInsets inset = UIEdgeInsetsMake(0, 10, 0, 0);
        if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            [cell setSeparatorInset:inset];
        }
        
        if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
            [cell setLayoutMargins:inset];
        }
    }
}

-(void)viewDidLayoutSubviews{
    [self setTableSeparatorInset];
}
#pragma mark UITableView delegate end

/**
 *  设置UITableView分割线空隙
 */
-(void)setTableSeparatorInset{
    UIEdgeInsets inset = UIEdgeInsetsMake(0, 10, 0, 0);
    if ([_listTable respondsToSelector:@selector(setSeparatorInset:)]) {
        [_listTable setSeparatorInset:inset];
    }
    
    if ([_listTable respondsToSelector:@selector(setLayoutMargins:)]) {
        [_listTable setLayoutMargins:inset];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
